import { login } from '@/services/api/auth';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Helmet, history } from '@umijs/max';

import { App } from 'antd';
import React, { useEffect } from 'react';
import Settings from '../../../../config/defaultSettings';

const Lang = () => {
  const langClassName = useEmotionCss(({ token }) => {
    return {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });
  return langClassName;
};

const Login: React.FC = () => {
  const { message } = App.useApp();
  useEffect(() => {
    localStorage.removeItem('token');
  }, []);
  // const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  // const [type, setType] = useState<string>('account');
  // const { initialState, setInitialState } = useModel('@@initialState');
  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });
  // const fetchUserInfo = async () => {
  //   const userInfo = await initialState?.fetchUserInfo?.();
  //   if (userInfo) {
  //     flushSync(() => {
  //       setInitialState((s) => ({
  //         ...s,
  //         currentUser: userInfo,
  //       }));
  //     });
  //   }
  // };
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      await login({
        ...values,
      });

      // const t = await getToken({
      //   ...values,
      //   tenantId: 1,
      //   grant_type: 'password',
      // });
      // localStorage.setItem('token', t.access_token);
      localStorage.setItem(
        'user_pas',
        JSON.stringify({
          ...values,
        }),
      );
      // if (t.access_token) {
      const defaultLoginSuccessMessage = '登录成功！';
      message.success(defaultLoginSuccessMessage);
      // await fetchUserInfo();
      // const urlParams = new URL(window.location.href).searchParams;
      // history.push(urlParams.get('redirect') || '/');
      history.replace('/tenant');
      return;
      // }
      // 错误逻辑后续处理
      // console.log(msg);
      // 如果失败去设置用户错误信息
      // setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  // const { status, type: loginType } = userLoginState;
  return (
    <div className={containerClassName}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>
      {/* <Lang /> */}
      <div className={Lang()}></div>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        {/* actions={['其他登录方式 :', <ActionIcons key="icons" />]} */}
        <LoginForm
          logo={`/images/logo.png`}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          title="场景联动"
          subTitle={'场景联动'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder={'用户名: super_admin'}
              rules={[
                {
                  required: true,
                  message: '用户名是必填项！',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'密码: super_admin'}
              rules={[
                {
                  required: true,
                  message: '密码是必填项！',
                },
              ]}
            />
          </>
        </LoginForm>
      </div>
    </div>
  );
};
// 解决message 报错问题
const MyLogin: React.FC = () => (
  <App>
    <Login />
  </App>
);
export default MyLogin;
